
var app = angular.module('App', ['ui.sortable','ngSanitize']);

//过滤html指令
app.filter('trustHtml', function ($sce) {
    return function (input) {
        return $sce.trustAsHtml(input);
    }
});

//创建当前页面元素
app.factory('createEl',function($compile){
    return function(els,scope){
        var html = '';
        $(els).each(function(index, el) {

            var style = JSON.stringify(el.style);
                style = style.replace('{','');
                style = style.replace('}','');
                style = style.replace(/,/g,';');
                style = style.replace(/"/g,'');
            if(el.type == 'text')
            {
                html += '<div el-drag style="'+style+'" type='+el.type+' id='+index+'>'+ el.html +'</div>';
            }else if (el.type == 'bj')
            {
                html += '<div style="'+style+'" type='+el.type+' id='+index+'></div>';
            }

        });
        var el = $compile(html)(scope);
        return el;
    }
});

//获取、设置当前元素下标
app.factory('el_index',function(){
    var a = 0;
    return {
        set:function(index){
            a = index;
        },
        get:function(){
            return a;
        },
    }
})

//添加元素默认数据格式服务
app.factory('defaultEl',function(){
    return function(){
        return {
            txt:{
                "type": "text",
                "html": "请输入内容",
                "style": {
                     "position":"absolute",
                     "left":"100px",
                     "top":"200px",
                     "color":"#fff",
                     "width":"auto",
                     "height":"auto",
                     "background":"#ddd"
                    }
            }
        }
    }
})

//promise 方式请求服务
app.factory('db', ['$http', '$q', function($http, $q) {
    return {
        getData: function(url) {
            var deferred = $q.defer();
            $http.get(url)
                .success(function(response, status, headers, config) {
                    deferred.resolve(response);
                }).error(function(response, status, headers, config){
                var errorObj = {
                    response: response,
                    status: status,
                    headers: headers,
                    config: config
                };
                deferred.reject(errorObj);
            });
            return deferred.promise;
        }
    }
}]);


//最父级指令
app.directive('editorScene',function(db){
    return{
        restrict: "EA",
        replace: 'true',
        controller:function($scope){

            var data = {
                "pages":[
                    [
                        {
                            "type": "text",
                            "html": "<div>测试呀呀呀呀1</div>",
                            "style": {
                                 "position":"absolute",
                                 "left":"0px",
                                 "top":"0px",
                                 "color":"#fff",
                                 "width":"200px",
                                 "height":"200px",
                                 "background":"#ddd"
                                }
                        },
                        {
                            "type": "text",
                            "html": "<div>测试呀呀呀呀2</div>",
                            "style": {
                                 "position":"absolute",
                                 "left":"230px",
                                 "top":"0px",
                                 "color":"#fff",
                                 "width":"100px",
                                 "height":"100px",
                                 "background":"#ddd"
                                }
                        },
                        {
                            "type": "text",
                            "html": "<div>测试呀呀呀呀3</div>",
                            "style": {
                                 "position":"absolute",
                                 "left":"0px",
                                 "top":"300px",
                                 "color":"#fff",
                                 "width":"100px",
                                 "height":"100px",
                                 "background":"#ddd"
                                }
                        },
                        {
                            "type": "bj",
                            "style": {
                                "background-image":" url(http://sjbz.fd.zol-img.com.cn/t_s320x510c/g5/M00/09/0A/ChMkJlhRE56IaK2lAAjhaFie8_cAAYjWgJq_DQACOGA390.jpg)",
                                "width": "100%",
                                "height": "486px",
                                "background-size": "cover",
                                "background-position": "50% 50%",
                                "background-origin": "content-box"
                                }
                        },
                    ],
                    [
                        {
                            "type": "text",
                            "html": "<div>测试呀呀呀呀1111</div>",
                            "style": {
                                 "position":"absolute",
                                 "left":"0px",
                                 "top":"0px",
                                 "color":"#fff",
                                 "width":"100px",
                                 "height":"100px",
                                 "background":"#ddd"
                                }
                        },
                        {
                            "type": "text",
                            "html": "<div>测试呀呀呀呀2222</div>",
                            "style": {
                                 "position":"absolute",
                                 "left":"230px",
                                 "top":"0px",
                                 "color":"#fff",
                                 "width":"100px",
                                 "height":"100px",
                                 "background":"#ddd"
                                }
                        },
                        {
                            "type": "text",
                            "html": "<div>测试呀呀呀呀333</div>",
                            "style": {
                                 "position":"absolute",
                                 "left":"0px",
                                 "top":"300px",
                                 "color":"#fff",
                                 "width":"100px",
                                 "height":"100px",
                                 "background":"#ddd"
                                }
                        }
                        ,{
                            "type": "bj",
                            "style": {
                                "background-image":"url(http://sjbz.fd.zol-img.com.cn/t_s320x510c/g5/M00/08/0A/ChMkJlhOPOSID8IiAAOAMW4LWcQAAYfLwIrRKwAA4BJ873.jpg)",
                                "width": "100%",
                                "height": "486px",
                                "background-size": "cover",
                                "background-position": "50% 50%",
                                "background-origin": "content-box"
                                }
                        }

                    ]


                ]
            };
            var _this                       = this;
            _this.data                      = data;
            _this.pages                     = data.pages;
            _this.thisPageIndex             = 0;
            _this.thisPageData              = _this.pages[0];
            _this.showElementBlock          = '';
            _this.editorContent             = '请输入内容';


        }
    }
});

//头部指令
app.directive("rkyHeader", function(createEl,defaultEl,el_index) {
    return {
        require:'^editorScene',
        templateUrl : "manage/ng-tpl/header.html",
        controller:function($scope){
            $scope.preview = function(){
                $scope.showElementBlock = "text";
            }

            $scope.addElement = function(el){
                $scope.showElementBlock = el;
            }

        },
        link:function(scope,elements,attrs,cntIns){
                scope.showElementBlock  = cntIns.showElementBlock;
                scope.thisPageIndex     = cntIns.thisPageIndex;
                scope.save = function(){
                    console.log(cntIns.data);
                };

                scope.addTxtElement = function(){
                    scope.showElementBlock = "text";
                    el_index.set(scope.thisPageData.length);
                    var txtObj = defaultEl().txt;
                    scope.thisPageData.push(txtObj)
                    scope.editorContent = txtObj.html;
                    var el = createEl(scope.thisPageData,scope);
                    $('#page').html(el);
                }
        },
    };
});

//文字编辑器指令
app.directive('contenteditable', function(el_index) {
   return {
       restrict: 'A' ,
       require: '?^editorScene',
       link: function(scope, element, attrs, ctrl) {
           // 创建编辑器
           var editor = new wangEditor('editor-trigger');
           editor.create();
           editor.onchange = function () {
               var index = el_index.get();
               var html  = editor.$txt.html();
                scope.thisPageData[index].html = html;
                $('#page > div').eq(index).html(html);
                console.log(index)
           };
       }
   };
});

//文字区指令
app.directive('rkyPanelText',function(){
    return{
        require:'^editorScene',
        templateUrl:'manage/ng-tpl/panel-text.html',
        controller:function($scope){},
        link:function(scope,elements,attrs,cntIns){
            scope.thisPageData = cntIns.thisPageData
            scope.editorContent = cntIns.editorContent;

        }
    }
});

//元素拖拽指令
app.directive('elDrag',function(el_index){
        return {
            require:'?^editorScene',
            controller:function($scope){},
            link:function(scope,elements,attrs,cntIns){

                elements.on('mousedown.drag',function(ev){
                    el_index.set(elements.attr('id'))
                    var index = el_index.get();
                    scope.$apply(function(){
                      scope.showElementBlock = 'text';
                      scope.editorContent = scope.thisPageData[index].html;
                    });

                    var This = this;
                    disX = ev.pageX - $(this).position().left;
                    disY = ev.pageY - $(this).position().top;

                    $(document).on('mousemove.drag',function(ev){
                        var x = ev.pageX - disX;
                        var t = ev.pageY - disY;
                        $(This).css('left',x);
                        $(This).css('top',t);

                        scope.thisPageData[index].style.left = x +'px';
                        scope.thisPageData[index].style.top  = t +'px';

                    });
                    $(document).on('mouseup',function(){
                        $(document).off('.drag');
                    });
                    return false;
                });
            }
        }
});

//图片区指令
app.directive('rkyPanelImg',function(){
        return {
            require:'^editorScene',
            templateUrl:'manage/ng-tpl/panel-img.html',
        }
})

//背景区指令
app.directive('rkyPanelBj',function(){
        return {
            require:'^editorScene',
            templateUrl:'manage/ng-tpl/panel-bj.html',
        }
})

//组件区指令
app.directive('rkyPanelComponent',function(){
        return {
            require:'^editorScene',
            templateUrl:'manage/ng-tpl/panel-component.html',
        }
})

//右侧页面列表指令
app.directive('rkyPageManager',function(createEl){
    return{
        require:'^editorScene',
        templateUrl:'manage/ng-tpl/page-list.html',
        controller:function($scope){},
        link:function(scope,elements,attrs,cntIns){
            scope.pages = cntIns.pages;
            scope.onPageChange = function(index){
                scope.showElementBlock          = '';
                scope.thisPageData  = scope.pages[index];
                scope.thisPageIndex = index;
                var el = createEl(scope.thisPageData,scope);
                $('#page').html(el);
            };

            scope.addpage = function(){
                scope.pages.push([]);
            };

            scope.onPageDel = function(index,$event){
                if(index === scope.pages.length-1 && index === scope.thisPageIndex)
                {
                    scope.thisPageIndex = index-1;
                }
                scope.pages.splice(index,1);
                scope.thisPageData  = scope.pages[scope.thisPageIndex];
                var el = createEl(scope.thisPageData,scope);
                $('#page').html(el);
                $event.stopPropagation();
            };
        }
    }
});

//中间编辑区指令
app.directive('rkyWorkspace',function($timeout,createEl){
    return{
        require:'^editorScene',
        templateUrl:'manage/ng-tpl/workspace.html',
        controller:function($scope){},
        link:function(scope,elements,attrs,cntIns){
            var el = createEl(cntIns.thisPageData,scope);
            $('#page').html(el);
        }
    }
});

//loading指令
app.directive('loading',function(){
        return {
            templateUrl:'manage/ng-tpl/loading.html',
            link:function(scope,elements,attrs,cntIns){
                $(function(){
                    $('.loading').hide();
                })

            }
        }
});
